<?php
namespace app\api\controller;

use app\common\controller\ApiController;
use think\App;
use \app\admin\traits\Curd;
use think\facade\Db;
use app\api\controller\Adv;
use app\api\model\Token;
use app\api\model\User as ModelUser;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;

class Shop extends ApiController
{
    protected $noNeedLogin = [
        "h5user_login",
        
    ];
    protected $mustLogin = [];
    protected $counter = 0;

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    //H5业务员登录
    public function h5user_login()
     {
        $param = $this->request->param();
        if (empty($param['username'])) {
            $this->error("登陆失败,账号不能为空");
        }
        if (empty($param['password'])) {
            $this->error("登陆失败,密码不能为空");
        }

        $flag = Db::name("system_admin")->where("username",$param["username"])->find();
        if(empty($flag)){
            $this->error("登陆失败,账户不存在");
        }
        if($flag["status"] == 0){
            $this->error("登陆失败,账户已锁定");
        }
        if($flag["password"] != password($param["password"])){
            $this->error("登陆失败,密码错误");
        }
        $token = Auth::makeToken();
        $userToken = new Token();
        $userToken->setToken($token, $flag["id"], $this->method);
        $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'h5user_id' => $flag["id"], 'h5userArr' => $flag]);
     }

     //统计数据
     public function statistics_data(){
        $order_money = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("status","in",[6])->sum("amount_collected");
        $order_count = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("status","in",[6])->count();
        $list["order_money"] = $order_money;
        $list["order_count"] = $order_count;
        $this->success('获取成功', $list);
     }
     
     //未下单订单列表
     public function notplaced_anorder_list(){
        $param = $this->request->param();
        $where = [];
        if(!empty($param['consignee']) && isset($param['consignee']))
        {
            $where[] = [
                ['consignee', 'like', "%{$param['consignee']}%"]
            ];
        }
        if(!empty($param['contact_phone']) && isset($param['contact_phone']))
        {
            $where[] = [
                ['contact_phone', '=', $param['contact_phone']]
            ];
        }
        
        //type 0全部  1未下单、2待审核、4审核驳回、5变更审核通过(审核通过、预约成功、已打印)
        if($param["type"] == 1){
            $newlist = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where($where)->whereIn("status","1,2,4")->order("create_time desc")->select()->toArray();
     
            $qwelis = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where($where)->whereIn("status","1")->where("change_status","2")->order("create_time desc")->select()->toArray();
            
            $list = array_merge($newlist,$qwelis);
           
            //二维数据去重
            $list = $this->unique_2d_array_by_key($list,"order_no");
        }else{
            $this->error("类型不存在");
        }
        foreach($list as $k=>$v){
            $v["create_time"] = date("Y-m-d H:i:s",$v["create_time"]);
            $list[$k] = $v;
        }
        $this->success("获取成功",$list);
     }

     function unique_2d_array_by_key($_2d_array, $unique_key) {
        $tmp_key[] = array();
        foreach ($_2d_array as $key => &$item) {
          if ( is_array($item) && isset($item[$unique_key]) ) {
            if ( in_array($item[$unique_key], $tmp_key) ) {
              unset($_2d_array[$key]);
            } else {
              $tmp_key[] = $item[$unique_key];
            }
          }
        }
        return $_2d_array;
      }

   

     //已通过订单列表
     public function passed_order_list(){
        $param = $this->request->param();

        $where = [];
        if(!empty($param['consignee']) && isset($param['consignee']))
        {
            $where[] = [
                ['consignee', 'like', "%{$param['consignee']}%"]
            ];
        }
        if(!empty($param['contact_phone']) && isset($param['contact_phone']))
        {
            $where[] = [
                ['contact_phone', '=', $param['contact_phone']]
            ];
        }

        //type 0全部  3审核通过、5预约成功、6出库成功  8未完结作废  9已完结作废 10已打印
        if($param["type"] == 1){
            $list = Db::name("order")->where("kahuna_id",$this->uid)->where($where)->where("delete_time",Null)->whereIn("status","3,5,6,8,9,10")->order("create_time desc")->paginate(10)->toArray();
            
        }else{
            $this->error("类型不存在");
        }
        foreach($list["data"] as $k=>$v){
            $v["create_time"] = date("Y-m-d H:i:s",$v["create_time"]);
            $list["data"][$k] = $v;
        }
        $this->success("获取成功",$list);
     }

     //新建订单
     public function addorder(){
        $post = $this->request->param();
        $session = Db::name("system_admin")->where("id",$this->uid)->find();
        //status 1保存   2确定下单->待审核
        if(empty($post['status'])){
            $this->error('状态不能为空');
        }
        if(empty($post['goodsArr'])){
            $this->error('商品不能为空');
        }
        if(empty($post['contact_phone'])){
            $this->error('联系电话不能为空');
        }
     
        if(empty($post['provinces'])){
            $this->error('省不能为空');
        }
       
        if(empty($post['consignee'])){
            $this->error('收货人不能为空');
        }
        if(empty($post['address'])){
            $this->error('收货地址不能为空');
        }
        if(empty($post['amount_collected'])){
            $this->error('收款金额不能为空');
        }
        if(empty($post['collection_voucher'])){
            $this->error('收款凭证不能为空');
        }
        $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$session['id'];
        $goodsArr = $post['goodsArr'];
        
        foreach($goodsArr as $k=>$v){
            $goods = Db::name("goods")->where("id",$v["gid"])->find();
            $v["good_bottom_price"] = $goods["bottom_price"];
            $goodsArr[$k] = $v;
        }
        $lisy = [];
        foreach($goodsArr as $ke=>$va){
            $flsst = bcmul($va["good_bottom_price"],$va["num"]);
            array_push($lisy,$flsst);
        }
        $order_bottom_price = array_sum($lisy);
        
        $data = [
            "order_bottom_price"=>$order_bottom_price,
            'order_no'=>$order_no,
            'kahuna_id'=>$session['id'],//负责人==下单人
            'kahuna_name'=>$session['username'],
            'remark'=>$post['remark'],//备注
            'consignee'=>$post['consignee'],//收货人
            'contact_phone'=>$post['contact_phone'],//联系电话
            'amount_collected'=>$post['amount_collected'],//收款金额
            'collection_voucher'=>$post['collection_voucher'],//收款凭证
        
            'provinces'=>$post['provinces'],//省
            'city'=>$post['city'],//市
            'area'=>$post['area'],//区
            'address'=>$post['address'],//详细地址
            "status"=>$post['status'],
            'create_time'=>time()
        ];
        
        Db::name("order")->insert($data);
        $orderId = Db::name('order')->getLastInsID();
        if($post['status'] == 2){
            //添加未读消息提示
            Db::name("message_prompt")->insert([
                "oid"=>$orderId,
                "type"=>1
            ]);
        }
        $this->txm($orderId);
        //添加商品信息 
        foreach($goodsArr as $k=>$v){
            $v["oid"] = $orderId;
            $goodsArr[$k] = $v;
            // $good_data = [
            //     "good_name"=>$v["good_name"],
            //     "gid"=>$v["gid"],
            //     "num"=>$v["num"],
            //     "good_bottom_price"=>$v["good_bottom_price"],
            //     "oid"=>$orderId
            // ];
        }
        Db::name('order_item')->insertAll($goodsArr); 
        $this->success("保存成功");
     }

    //生成条形码
    public function txm($oid){
        $bar_code_num = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $oid;
         /* getBarcode($code, $type, $widthFactor = 2, $totalHeight = 30, $color = 'black')
        code：条形码数据

        type：条形码的类型，使用在类中定义的常量，具体参数可参考github

        widthFactor：条形码的宽度

        totalHeight：条形码高度

        color：条形码的颜色*/

        //生成png、jpg类型的图片条形码
        //$generatorJPG = new \Picqer\Barcode\BarcodeGeneratorJPG(); 
        $generator = new \Picqer\Barcode\BarcodeGeneratorPNG();

        $barcode = $generator->getBarcode($bar_code_num, $generator::TYPE_CODE_128);
        $filename = time().rand(0, 1000).".png";
        //条形码图片保存路由
        file_put_contents("crmimg/".$filename,$barcode);
        $upload_path = "crmimg/";
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        
        //生成图片路由
        $save_path =$domain.'/' . $upload_path .$filename;

        Db::name("order")->where("id",$oid)->update(["bar_code_img"=>$save_path,"bar_code_num"=>$bar_code_num]);

    }

    //编辑订单
    public function editorder(){
        $post = $this->request->param();
        //status 1保存   2确定下单->待审核
        $post = $this->request->param();
            $flag = Db::name("order")->where('id',$post['id'])->find();
            if(empty($post['goodsArr'])){
                $this->error('商品不能为空');
            }
            if(empty($post['contact_phone'])){
                $this->error('联系电话不能为空');
            }
            //dump(!preg_match("/^1[34578]\d{9}$/", $post['contact_phone']));die;
            // if (!preg_match("/^1[34578]\d{9}$/", $post['contact_phone'])) {
            //     $this->error('联系电话格式不正确');
            // } 
            if(empty($post['provinces'])){
                $this->error('省不能为空');
            }
        
            if(empty($post['consignee'])){
                $this->error('收货人不能为空');
            }
            if(empty($post['address'])){
                $this->error('收货地址不能为空');
            }
            if(empty($post['amount_collected'])){
                $this->error('收款金额不能为空');
            }
            if(empty($post['collection_voucher'])){
                $this->error('收款凭证不能为空');
            }
            $goodsArr = $post['goodsArr'];
            foreach($goodsArr as $k=>$v){
                $goods = Db::name("goods")->where("id",$v["gid"])->find();
                $v["good_bottom_price"] = $goods["bottom_price"];
                $goodsArr[$k] = $v;
            }
            $lisy = [];
            foreach($goodsArr as $ke=>$va){
                $flsst = bcmul($va["good_bottom_price"],$va["num"]);
                array_push($lisy,$flsst);
            }
            $order_bottom_price = array_sum($lisy);
      
            //status 1保存   2确定下单->待审核
            if(empty($post['status'])){
                $this->error('状态不能为空');
            }
            $data = [
                "order_bottom_price"=>$order_bottom_price,
                'remark'=>$post['remark'],//备注
                'consignee'=>$post['consignee'],//收货人
                'contact_phone'=>$post['contact_phone'],//联系电话
                'amount_collected'=>$post['amount_collected'],//收款金额
                'collection_voucher'=>$post['collection_voucher'],//收款凭证
               
                'provinces'=>$post['provinces'],//省
                'city'=>$post['city'],//市
                'area'=>$post['area'],//区
                'address'=>$post['address'],//详细地址
                "status"=>$post['status']
            ];
                //添加未读消息提示
            if($post['status'] == 2){
                Db::name("message_prompt")->insert([
                    "oid"=>$post['id'],
                    "type"=>1
                ]);
            }
       
        try {
            Db::name("order")->where('id',$post['id'])->update($data);
            Db::name('order_item')->where("oid",$post['id'])->delete();
            //编辑商品信息 
            foreach($goodsArr as $k=>$v){
                $v["oid"] = $post['id'];
                $goodsArr[$k] = $v;
            }
            Db::name('order_item')->insertAll($goodsArr); 
        } catch (\Exception $e) {
            $this->error('保存失败:' . $e->getMessage());
        }
        $this->success('保存成功') ;
    }

     //商品类型
     public function getgood_type(){
        $good_type = Db::name("good_type")->order("id desc")->select()->toArray();
        $this->success("获取成功",$good_type);
     }
     
     //省
     public function get_provinces(){
        $list = Db::name("area")->where("level",0)->order("id asc")->field("id,name")->select()->toArray();
        $this->success("获取成功",$list);
     }
     //市
     public function city(){
        $post = $this->request->param();
        if(empty($post['pid'])){
            $this->error('省id不能为空');
        }
        $city = Db::name("area")->where("pid",$post['pid'])->order("id asc")->field("id,name")->select()->toArray();
        $this->success("获取成功",$city);
        
    }
    //区
    public function area(){
        $post = $this->request->param();
        if(empty($post['cid'])){
            $this->error('市id不能为空');
        }
        $quarr = Db::name("area")->where("pid",$post['cid'])->order("id asc")->field("id,name")->select()->toArray();
        $this->success("获取成功",$quarr);
      
    }

    //商品列表
    public function get_goodsarr(){
        $goods = Db::name("goods")->where("status",0)->order("id desc")->select()->toArray();
        foreach ($goods as $k => $v){
            //分类
            $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
            if(!empty($good_type)){
                $v['good_type_name'] = $good_type['title'];
            }else{
                $v['good_type_name'] = "";
            }
           

            $goods[$k] = $v;
        }
        $this->success("获取成功",$goods);
    }

    //商品搜索
    public function good_search(){
        $param = $this->request->param();
     
        $where = [];
        if(!empty($param['title']) && isset($param['title']))
        {
            $where[] = [
                ['title', 'like', "%{$param['title']}%"]
            ];
        }
        if(!empty($param['good_type_id']) && isset($param['good_type_id']))
        {
            $where[] = [
                ['good_type_id', '=', $param['good_type_id']]
            ];
        }
        // if(empty($where)){
        //     $this->success("获取成功",[]);
        // }
        $goods = Db::name("goods")->where("status",0)->where($where)->order("id desc")->select()->toArray();
        foreach ($goods as $k => $v){
            //分类
            $good_type = Db::name('good_type')->where('id',$v['good_type_id'])->field('title')->find();
            $v['good_type_name'] = $good_type['title'];

            $goods[$k] = $v;
        }
        $this->success("获取成功",$goods);
    }

    //订单搜索
    public function order_search(){
        $param = $this->request->param();
        if(empty($param["type"])){
            $this->error("类型不存在");
        }
        $where = [];
        if(!empty($param['consignee']) && isset($param['consignee']))
        {
            $where[] = [
                ['consignee', 'like', "%{$param['consignee']}%"]
            ];
        }
        if(!empty($param['contact_phone']) && isset($param['contact_phone']))
        {
            $where[] = [
                ['contact_phone', '=', $param['contact_phone']]
            ];
        }
        // if(empty($where)){
        //     $this->success("获取成功",[]);
        // }
        //type 1订单 2变更单
        if($param["type"] == 1){
            $order = Db::name("order")->where($where)->where("delete_time",Null)->where("kahuna_id",$this->uid)->order("id desc")
            ->paginate(10)->each(function($item){
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                return $item;
            });
        }elseif($param["type"] == 2){
            $order = Db::name("order")->where($where)->where("delete_time",Null)->where("kahuna_id",$this->uid)->where("is_change",2)->order("id desc")
            ->paginate(10)->each(function($item){
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                return $item;
            });
           
        }else{
            $this->error("类型不存在");
        }
        $order = $order->toArray();
        $this->success("获取成功",$order);
    }

    //订单详情 
    public function ord_detail(){
        $param = $this->request->param();
        $row = Db::name("order")->where("id",$param["id"])->find();
     
        //收款凭证
      //  $collection_voucher = explode(",",$row["collection_voucher"]);
    
        $order_item = Db::name("order_item")->where("oid",$param["id"])->select()->toArray();
     
        //$row["collection_voucher"] = $collection_voucher;
        //收款凭证
        if(!empty($row["collection_voucher"])){
            $row["collection_voucher"] = explode(",",$row["collection_voucher"]);
        }
        
        //未完结作废图片
        if(!empty($row["void_picture"])){
            $row["void_picture"] = explode(",",$row["void_picture"]);
        } 
        $row["order_item"] = $order_item;
        $row["create_time"] = date("Y-m-d H:i:s",$row["create_time"]);
        $row["change_application_time"] = date("Y-m-d H:i:s",$row["change_application_time"]);
        $this->success('获取成功', $row);
    }

    
     //取消订单
     public function cancel_order(){
        $post = $this->request->param();
        $ret = Db::name("order")->where('id', $post['id'])->where('status', 2)->find();
        if (empty($ret)) {
            $this->error('当前订单状态不能取消');
        }
        Db::name("order")->where('id', $post['id'])->update(["status"=>7]);
        $this->success('取消成功', '');
    }

     //变更订单申请
     public function change_information(){
        $post = $this->request->param();
        $ret = Db::name("order")->where('id', $post['id'])->where('status', "in","3,5,6,10")->find();
        if (empty($ret)) {
            $this->error('当前订单状态不能变更');
        }
        //1收货信息，2订单商品
        if(empty($post['change_info'])){
            $this->error('变更信息不能为空');
        }
        Db::name("order")->where('id', $post['id'])->update(["is_change"=>2,"change_info"=>$post["change_info"],"change_status"=>1,"change_application_time"=>time()]);
        //添加未读消息提示
        Db::name("message_prompt")->insert([
            "oid"=>$post['id'],
            "type"=>2
        ]);
        $this->success('申请成功', '');
    }

    //变更订单列表
    public function change_order_list(){
        $param = $this->request->param();
        //type 0全部 1、待审核 2、通过，3驳回，5预约成功
        if($param["type"] == 0){
            $list = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("is_change",2)->order("create_time desc")->paginate(10)->toArray();
        }elseif($param["type"] == 1){
            $list = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("change_status",1)->where("is_change",2)->order("create_time desc")->paginate(10)->toArray();
        }elseif($param["type"] == 2){
            $list = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("change_status",2)->where("is_change",2)->order("create_time desc")->paginate(10)->toArray();
        }elseif($param["type"] == 3){
            $list = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("change_status",3)->where("is_change",2)->order("create_time desc")->paginate(10)->toArray();
        }elseif($param["type"] == 5){
            $list = Db::name("order")->where("kahuna_id",$this->uid)->where("delete_time",Null)->where("change_status",2)->where("status",5)->where("is_change",2)->order("create_time desc")->paginate(10)->toArray();
        }else{
            $this->error("类型不存在");
        }
        foreach($list["data"] as $k=>$v){
            $v["change_application_time"] = date("Y-m-d H:i:s",$v["change_application_time"]);
            $list["data"][$k] = $v;
        }
        $this->success("获取成功",$list);
    }

     //变更订单通过
     public function app_change_order_review(){
            $admin = Db::name("system_admin")->where("id",$this->uid)->find();
            $post = $this->request->param();
            $ret = Db::name("order")->where('id', $post['id'])->where('change_status', 1)->find();
            if (empty($ret)) {
                $cflsg = Db::name("order")->where('id', $post['id'])->where('status', 6)->find();
                //查看订单商品是否出库，如果出库的话，就得作废入库    判断订单状态是否为6  6位已出库
                if(!empty($cflsg)){
                    //订单商品作废入库
                    $order_item = Db::name("order_item")->where("oid",$post["id"])->field("gid,good_name,num")
                                ->paginate()->each(function($item){
                                    $goods = Db::name("goods")->where("id",$item["gid"])->find();
                                    $good_type = Db::name("good_type")->where("id",$goods["good_type_id"])->find();
                                    $item["good_type_id"] = $good_type["id"];
                                    $item["good_type_name"] = $good_type["title"];
                                    $item["good_bar_code"] = $goods["bar_code"];
                                    return $item;
                                });
                    $order_item = $order_item->toArray();
                    $goodsw_item = $order_item["data"];
                
                    //入库单号
                    $receipt_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$admin['id'];
        
                    $data_zf = [
                        "receipt_no"=>$receipt_no,
                        "receipt_name"=>"系统作废订单商品入库",
                        "status"=>2,
                        "receipt_type"=>2,
                        "warehousing_time"=>date("Y-m-d H:i:s",time()),
                        "receipt_username"=>$admin["username"],//入库人id
                        "receipt_id"=>$admin["id"],//入库人姓名
                    ];
                    Db::name("goods_warehousing")->insert($data_zf);
                    $goodsw_id = Db::name('goods_warehousing')->getLastInsID();
                    //添加入库商品信息 
                    foreach($goodsw_item as $k=>$v){
                        $v["goods_warehousing_id"] = $goodsw_id;
                        $goodsw_item[$k] = $v;
                    }
                    Db::name('goods_warehousing_item')->insertAll($goodsw_item); 
                    foreach($goodsw_item as $k=>$ve){
                        //添加出入库明细
                        $data_crk = [
                            "data_id"=>$goodsw_id,//数据id
                            'odd_numbers'=>$receipt_no,//单号
                            "gid"=>$ve["gid"],
                            "good_type_id"=>$ve["good_type_id"],
                            "good_type_name"=>$ve["good_type_name"],
                            "receipt_issue_type"=>2,//1采购入库 2作废入库 3销售出库 4盘赢入库 5盘亏出库
                            "create_time"=>time(),
                            "receipt_issue_num"=>$ve["num"] //出入库数量
                        ];
                        Db::name("receipt_issue_detailed")->insert($data_crk);
                        //修改商品库存
                        Db::name("goods")->where("id",$ve["gid"])->inc("stock",$ve["num"])->update();
                        Db::name("goods")->where("id",$ve["gid"])->dec("sales_volume",$ve["num"])->update();
                        //出库订单变更状态
                        Db::name("order")->where('id', $post['id'])->update(["status"=>8]);
                        //添加未读消息提示
                        Db::name("message_prompt")->insert([
                            "oid"=>$post['id'],
                            "type"=>3
                        ]);
                    }
                    $this->success('操作成功', '');
                }else{
                    $this->error('此订单不能作废', '');
                }
            }
            Db::name("order")->where('id', $post['id'])->update(["change_status"=>2,"is_edit"=>2,"change_auditor"=>$admin["username"],"change_auditor_id"=>$admin["id"]]);
        
            $this->success('操作成功', '');
        
    }

    //上传图片
    public function upload()
    {
        $file = request()->file('file');
        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        try {
            validate('app\api\validate\Upload')
                ->scene('img')
                ->check(['file' => $file]);
            $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
            $url = request()->domain() . '/' . $savename;
            $this->success('上传成功',$url);
        } catch (\think\exception\ValidateException $e) {
            $this->error('上传失败',$e->getMessage());
        }
    }


    
     //已通过订单列表
     public function after_sales_list(){
        $param = $this->request->param();

        $where = [];
        if(!empty($param['consignee']) && isset($param['consignee']))
        {
            $where[] = [
                ['consignee', 'like', "%{$param['consignee']}%"]
            ];
        }
        if(!empty($param['contact_phone']) && isset($param['contact_phone']))
        {
            $where[] = [
                ['contact_phone', '=', $param['contact_phone']]
            ];
        }
        //type  8未完结作废  
        $list = Db::name("order")->where("kahuna_id",$this->uid)->where($where)->where("delete_time",Null)->where("status","8")->order("create_time desc")->paginate(10)->toArray();
    
        foreach($list["data"] as $k=>$v){
            $v["create_time"] = date("Y-m-d H:i:s",$v["create_time"]);
            $list["data"][$k] = $v;
        }
        $this->success("获取成功",$list);
     }
    
 
   
}
